package biz.yfsoft.app.fastframework.kit;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

public class RestKit {

	public static String connection(String urlPath, String method, Map<String, String> headers, Object dataObj) 
			throws IOException{
		try {
			URL url = new URL(urlPath);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod(method);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			for (Iterator<String> iterator = headers.keySet().iterator(); iterator.hasNext();) {
				String key = iterator.next();
				conn.setRequestProperty(key, headers.get(key));
			}
			byte[] bytes = dataObj.toString().getBytes("utf-8");
			OutputStream out = conn.getOutputStream();
			out.write(bytes, 0, bytes.length);
			out.flush();
			
			int code = conn.getResponseCode();
			ByteArrayOutputStream daos = new ByteArrayOutputStream();
			if(code == 200){
				InputStream in = conn.getInputStream();
				byte[] result = new byte[1024];
				int count = -1;
				while (true) {
					count = in.read(result);
					if(count == -1)
						break;
					daos.write(result, 0, result.length);
				}
				in.close();
				out.close();
				return daos.toString();
			}else{
				InputStream in = conn.getErrorStream();
				byte[] result = new byte[1024];
				int count = -1;
				while (true) {
					count = in.read(result);
					if(count == -1)
						break;
					daos.write(result, 0, result.length);
				}
				in.close();
				out.close();
				throw new IOException(daos.toString());
			}
			
		} catch (IOException e) {
			throw e;
		}
	}
	
	public static void main(String[] args) throws IOException{
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("X-AVOSCloud-Application-Id", "2lco5zd9yrym993r0li8dhipksuizp2miv9c4i8nedadfhqk");
		headers.put("X-AVOSCloud-Application-Key", "o9w9674ouz01usc8lmlophb6cgdjsaki2pgvc409yjlqp1ra");
		headers.put("Content-Type", "application/json");
		JSONObject jo = new JSONObject();
		jo.put("mobilePhoneNumber", "13770683580");
		jo.put("template", "template1");
		System.out.println(connection("https://api.leancloud.cn/1.1/requestSmsCode", "POST", headers, jo));
		
	}
}
